﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.Extensions;
using Domain.Base;

namespace Domain
{
	public class Exercise : BaseEntity
	{
		public String DisplayName { get; set; }
		public List<ExerciseLog> ExerciseLogs { get; set; }

		public Double GetRecordWeight()
		{
			if (ExerciseLogs.IsNullOrEmpty())
				return 0.0;

			return ExerciseLogs.Max(x => x.MaxWeight());
		}

		public ExerciseLog GetLastLog()
		{
			if (ExerciseLogs.IsNullOrEmpty())
				return ExerciseLog.GetEmpty();

			return ExerciseLogs.OrderBy(x => x.LogDate).LastOrDefault() ?? ExerciseLog.GetEmpty();
		}

		public ExerciseLog GetBeforeDate(DateTime date)
		{
			if (ExerciseLogs.IsNullOrEmpty())
				return ExerciseLog.GetEmpty();

			return ExerciseLogs.OrderByDescending(x => x.LogDate).FirstOrDefault(x => x.LogDate < date) ?? ExerciseLog.GetEmpty();
		}

		public ExerciseLog FindExerciseLogBySetLogId(Guid setLogId)
		{
			if (ExerciseLogs.IsNullOrEmpty())
				throw new ArgumentNullException("ExerciseLogs are empty");

			foreach (var exerciseLog in ExerciseLogs)
			{
				var bla = exerciseLog.Sets.FirstOrDefault(x => x.Id == setLogId);
				if (bla != null)
					return exerciseLog;
			}
			throw new ArgumentOutOfRangeException();
		}

		public void Remove(SetLog setLog)
		{
			var exerciseLog = FindExerciseLogBySetLogId(setLog.Id);
			exerciseLog.Sets.Remove(setLog);
		}

		public double GetRecordVolume()
		{
			if (ExerciseLogs.IsNullOrEmpty())
				return 0.0;

			return ExerciseLogs.Max(x => x.GetVolume());
		}

		public List<SetLog> GetAllSets()
		{
			var res = new List<SetLog>();
			if (!ExerciseLogs.IsNullOrEmpty())
			{
				foreach (var exerciseLog in ExerciseLogs)
				{
					if (exerciseLog.Sets.IsNullOrEmpty())
						continue;

					res.AddRange(exerciseLog.Sets);
				}
			}

			return res;
		}
	}
}
